package com.yl.order;

import com.net.yl.ApiRepository;
import com.yl.order.helper.SmallApkHelper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler mDefaultCrashHandler;

    private CrashHandler() {
    }

    private static final class HandlerHolder {
        static final CrashHandler handler = new CrashHandler();
    }

    public static CrashHandler getsInstance() {
        return HandlerHolder.handler;
    }

    public void init() {
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 这个是最关键的函数，当程序中有未被捕获的异常，系统将会自动调用uncaughtException方法
     * thread为出现未捕获异常的线程，ex为未捕获的异常，有了这个ex，我们就可以得到异常信息
     *
     * @param thread
     * @param ex
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        dumpExceptionToSDCard(ex);
        SmallApkHelper.pullMeLaterActivityMode(1500);
        mDefaultCrashHandler.uncaughtException(thread, ex);
    }

    private void dumpExceptionToSDCard(Throwable ex) {
        new Thread(() -> {
            File dir = new File(Constants.FILE_LOG_CRASH_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd_HH-mm-ss", Locale.CHINA);
            String time = sdf.format(new Date());
            File file = new File(dir, time + ".txt");
            try {
                boolean find = true;
                if (!file.exists()) {
                    find = file.createNewFile();
                }
                if (!find) {
                    return;
                }
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                ex.printStackTrace(pw);
                pw.close();
                if (!BuildConfig.DEBUG) {
                    ApiRepository.getInstance().uploadCrashLog(file);
                }
            } catch (Exception ignore) {

            }
        }).start();
    }
}
